package hikari.gui;

import com.gooddies.swing.JpDialog;
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;

/**
 * @author sad
 */
public abstract class AskDialog extends JpDialog {

    private boolean modalResult = false;

    public AskDialog(Window parent) {
        super(parent);
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        setModal(true);
    }

    private void init() {
        getContentPane().removeAll();
        getContentPane().setLayout(new BorderLayout());
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        createContent(content);
        getContentPane().add(content);

        JPanel buttonsPanel = new JPanel();
        buttonsPanel.setLayout(new MigLayout());

        JButton okButton = new JButton("OK");
        okButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                internalOnOK();
            }
        });

        buttonsPanel.add(okButton);
        JButton cancelButton = new JButton("Cancel");
        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                internalOnCancel();
            }
        });

        buttonsPanel.add(cancelButton);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                internalOnCancel();
            }
        });
        getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
        pack();
    }

    public boolean showDialog() {
        init();
        modalResult = false;
        setVisible(true);
        return modalResult;
    }

    private void internalOnOK() {
        if (dialogValidation()) {
            if (onOK()) {
                modalResult = true;
                setVisible(false);
                dispose();
            }
        }
    }

    private void internalOnCancel() {
        if (onCancel()) {
            modalResult = false;
            setVisible(false);
            dispose();
        }
    }

    protected abstract void createContent(JPanel container);

    /**
     * Invokes after user press OK
     */
    protected boolean dialogValidation() {
        return true;
    }

    protected boolean onCancel() {
        return true;
    }

    protected abstract boolean onOK();
}
